const { prisma } = require('../config/prisma');

async function debugTimezone() {
  try {
    const now = new Date();
    console.log('=== 时区调试 ===\n');
    console.log(`JavaScript now: ${now.toLocaleString('zh-CN')}`);
    console.log(`JavaScript now ISO: ${now.toISOString()}`);
    console.log(`JavaScript now timestamp: ${now.getTime()}\n`);

    // 测试查询 ID 43
    const listing = await prisma.listings.findUnique({
      where: { id: BigInt(43) }
    });

    if (listing && listing.auto_publish_at) {
      console.log(`数据库 auto_publish_at: ${listing.auto_publish_at.toLocaleString('zh-CN')}`);
      console.log(`数据库 auto_publish_at ISO: ${listing.auto_publish_at.toISOString()}`);
      console.log(`数据库 auto_publish_at timestamp: ${listing.auto_publish_at.getTime()}\n`);

      console.log(`now > auto_publish_at: ${now > listing.auto_publish_at}`);
      console.log(`时间差 (毫秒): ${now - listing.auto_publish_at}`);
      console.log(`时间差 (分钟): ${Math.floor((now - listing.auto_publish_at) / 1000 / 60)}\n`);
    }

    // 测试查询条件
    console.log('测试查询条件...\n');

    const testQuery = await prisma.listings.findMany({
      where: {
        id: BigInt(43),
        audit_status: 'PENDING',
        audit_admin_id: null,
        audit_time: null,
        NOT: {
          audit_comment: 'USER_OFFLINE'
        },
        auto_publish_at: {
          lte: now,
          not: null
        }
      }
    });

    console.log(`查询结果数量: ${testQuery.length}`);

    if (testQuery.length === 0) {
      console.log('\n❌ 查询条件不匹配!让我们逐个检查条件:\n');

      const listing43 = await prisma.listings.findUnique({
        where: { id: BigInt(43) }
      });

      console.log(`audit_status === 'PENDING': ${listing43.audit_status === 'PENDING'}`);
      console.log(`audit_admin_id === null: ${listing43.audit_admin_id === null}`);
      console.log(`audit_time === null: ${listing43.audit_time === null}`);
      console.log(`audit_comment !== 'USER_OFFLINE': ${listing43.audit_comment !== 'USER_OFFLINE'}`);
      console.log(`auto_publish_at !== null: ${listing43.auto_publish_at !== null}`);
      console.log(`auto_publish_at <= now: ${listing43.auto_publish_at <= now}`);

      // 单独测试时间比较
      console.log('\n直接比较时间:');
      const directCompare = await prisma.$queryRaw`
        SELECT
          id,
          auto_publish_at,
          NOW() as current_time,
          auto_publish_at <= NOW() as is_expired
        FROM listings
        WHERE id = 43
      `;
      console.log('SQL 查询结果:', directCompare);
    } else {
      console.log('✅ 查询条件匹配!');
    }

  } catch (error) {
    console.error('调试失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

debugTimezone();
